package com.ph.clouds.tracker.ex;

import android.content.Context;
import android.util.AttributeSet;
import android.widget.EditText;


import androidx.annotation.NonNull;

import com.ph.clouds.tracker.Tracker;
import com.ph.clouds.tracker.entity.TrackParamsEntity;


/**
 * @Author yushuangjiang
 * @Time 2021/8/3 17:36
 * @Description： 支持统计输入时间的输入框
 */
public class TrackTimeEditText extends EditText {

    public TrackTimeEditText(Context context) {
        super(context);
    }

    public TrackTimeEditText(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public TrackTimeEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    private long startTime = 0L;

    /**
     * @param track 埋点参数
     */
    public void addFocusTrackListener(@NonNull TrackParamsEntity track) {
        setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                //得到焦点 保留开始时间
                startTime = System.currentTimeMillis();
            } else {
                //失去焦点后计算时间 埋点
                long now = System.currentTimeMillis();
                track.setEventTime(Math.abs(now - startTime));
                Tracker.getInstance().track(track);
            }
        });
    }
    public void addFocusAndTextTrackListener(@NonNull final TrackParamsEntity track) {
        setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                //得到焦点 保留开始时间
                startTime = System.currentTimeMillis();
            } else {
                //失去焦点后计算时间 埋点
                long now = System.currentTimeMillis();
                track.setEventTime(Math.abs(now - startTime));
                track.setRemark(getEditableText().toString());
                Tracker.getInstance().track(track);
            }
        });
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        clearFocus();
    }
}
